package com.ybb.vue.service.Impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ybb.vue.common.Result;
import com.ybb.vue.common.util.CreateRandOdd;
import com.ybb.vue.domain.dto.GoodsInAddDto;
import com.ybb.vue.entity.Approval;
import com.ybb.vue.entity.GoodsIn;
import com.ybb.vue.entity.GoodsInventory;
import com.ybb.vue.mapper.GoodsInventoryMapper;
import com.ybb.vue.service.ApprovalService;
import com.ybb.vue.service.GoodsInService;
import com.ybb.vue.mapper.GoodsInMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
* @author apple
* @description 针对表【goods_in(物资入库表)】的数据库操作Service实现
* @createDate 2023-04-04 16:50:59
*/
@Service
public class GoodsInServiceImpl extends ServiceImpl<GoodsInMapper, GoodsIn>
implements GoodsInService{

    @Autowired
    private GoodsInventoryMapper goodsInventoryMapper;

    @Autowired
    private ApprovalService approvalService;

    @Override
    public Result add(GoodsInAddDto goodsInAddDto) {
        GoodsInventory goodsInventory = goodsInventoryMapper.selectOne(new QueryWrapper<GoodsInventory>().lambda().eq(GoodsInventory::getGoodsType, goodsInAddDto.getGoodsType()).eq(GoodsInventory::getGoodsName, goodsInAddDto.getGoodsName()));
        if ("0".equals(goodsInAddDto.getInType())) {
            if (goodsInventory != null) {
                return Result.error("-1", "仓库中已存在该类物资，请选择添加物资操作");
            }
        }
        if ("1".equals(goodsInAddDto.getInType())) {
            if (goodsInventory == null) {
                return Result.error("-1", "仓库中不存在该类物资，请选择新增物资操作");
            }
        }
        GoodsIn goodsIn = new GoodsIn();
        BeanUtils.copyProperties(goodsInAddDto, goodsIn);
        goodsIn.setInStatus("0");
        goodsIn.setInTime(new Date());
        goodsIn.setHandler(SecurityContextHolder.getContext().getAuthentication().getName());
        goodsIn.setInOdd(CreateRandOdd.createRandOdd());
        this.save(goodsIn);

        // 写入审核表
        Approval approval = new Approval();
        approval.setSubjectId(goodsIn.getId());
        if(goodsInAddDto.getInType().equals("0")){
            // 新增入库
            approval.setSubjectSource("INA");
        }else{
            // 添加入库
            approval.setSubjectSource("INC");
        }
        approval.setApprovalStatus("0");
        approvalService.save(approval);

        // 操作记录
//        String content = "操作了入库单表，【新增】了1条记录，记录id为：" + goodsIn.getId();
//        OperationRecordsUtils.createOperationRecords(content);
        return Result.success();
    }
}
